package vip.bblog.quartz.service.impl;

import com.alibaba.fastjson.JSON;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import vip.bblog.common.utils.BaseResult;
import vip.bblog.quartz.entity.QuartzJob;
import vip.bblog.quartz.job.MyJob;
import vip.bblog.quartz.service.JobService;

/**
 * @author <a href="1396513066@qq.com">Yu Yong</a>
 * @version 1.0
 * @date 2019年06月17日 16:54
 * @desc jobServiceImpl job调度中心
 */
@Service
public class JobServiceImpl implements JobService {

    private static final Logger log = LoggerFactory.getLogger("JobServiceImpl");

    private static final String JOB_DATA_KEY = "JOB_DATA_KEY";

    @Autowired
    private Scheduler scheduler;

    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 添加任务
     *
     * @param quartzJob
     */
    @Override
    public void saveOrUpdateJob(QuartzJob quartzJob) {

        String jobName = quartzJob.getName();
        String groupName = quartzJob.getGroup();

        JobKey jobKey = JobKey.jobKey(jobName, groupName);
        JobDetail jobDetail = JobBuilder.newJob(MyJob.class).storeDurably()
                .withDescription(quartzJob.getDescription()).withIdentity(jobKey).build();

        jobDetail.getJobDataMap().put(JOB_DATA_KEY, quartzJob);

        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(quartzJob.getCron());
        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(jobName, groupName).withSchedule(cronScheduleBuilder)
                .forJob(jobKey).build();

        try {
            boolean exists = scheduler.checkExists(jobKey);
            if (exists) {
                scheduler.rescheduleJob(TriggerKey.triggerKey(jobName, groupName), cronTrigger);
                scheduler.addJob(jobDetail, true);
            } else {
                scheduler.scheduleJob(jobDetail, cronTrigger);
            }
        } catch (SchedulerException e) {
            e.printStackTrace();
            log.error("新增或修改job异常", e);
        }
    }

    /**
     * 删除任务
     *
     * @param quartzJob
     * @throws SchedulerException
     */
    @Override
    public void deleteJob(QuartzJob quartzJob) {
        JobKey jobKey = JobKey.jobKey(quartzJob.getName(), quartzJob.getGroup());
        try {
            scheduler.pauseJob(jobKey);
            scheduler.unscheduleJob(TriggerKey.triggerKey(quartzJob.getName(), quartzJob.getGroup()));
            scheduler.deleteJob(jobKey);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    /**
     * 暂停任务
     *
     * @param quartzJob
     */
    @Override
    public void pauseJob(QuartzJob quartzJob) {
        try {
            scheduler.pauseJob(JobKey.jobKey(quartzJob.getName(), quartzJob.getGroup()));
        } catch (SchedulerException e) {
            e.printStackTrace();
            log.error("暂停job异常", e);
        }
    }

    /**
     * 恢复任务
     *
     * @param quartzJob
     */
    @Override
    public void resumeJob(QuartzJob quartzJob) {
        try {
            scheduler.resumeJob(JobKey.jobKey(quartzJob.getName(), quartzJob.getGroup()));
        } catch (SchedulerException e) {
            e.printStackTrace();
            log.error("恢复job异常", e);
        }
    }

    /**
     * 执行任务
     *
     * @param jobDataMap
     */
    @Override
    public void doJob(JobDataMap jobDataMap) {
        QuartzJob quartzJob = (QuartzJob) jobDataMap.get(JOB_DATA_KEY);

        String name = quartzJob.getName();

    }

    @Override
    public BaseResult<Object> list() {
        QuartzJob quartzJob = new QuartzJob();
        String test = "{ \"code\": 200000, \"data\": { \"serialId\": \"\", \"id\": \"4daff73ee8dc410f8dc917b5875fe4dd\", \"linkMapId\": \"china:sicuan\", \"type\": \"POLYGON\", \"geoJson\": \"{}\", \"userId\": \"002\", \"isDelete\": \"\" }, \"message\": \"成功\" }";
        quartzJob.setParameter(JSON.parseObject(test));
        quartzJob.setName("hello");
        quartzJob.setGroup("group");
        return BaseResult.successWithData(quartzJob);
    }
}
